package ee.android.kinokavad.utils;

import java.util.EnumMap;
import java.util.Map;

import android.content.Context;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FontUtils {

	private enum FontType {
		BOLD("fonts/Roboto/Roboto-Bold.ttf"),
		LIGHT("fonts/Roboto/Roboto-Light.ttf"),
		CONDENSED("fonts/Roboto/Roboto-Condensed.ttf"),
		NORMAL("fonts/Roboto/Roboto-Regular.ttf");

		private final String path;

		FontType(String path) {
			this.path = path;
		}

		public String getPath() {
			return path;
		}
	}

	/* cache for loaded Roboto typefaces*/
	private static Map<FontType, Typeface> typefaceCache = new EnumMap<FontType, Typeface>(FontType.class);

	/**
	 * Creates Roboto typeface and puts it into cache
	 */
	private static Typeface getRobotoTypeface(Context context, FontType fontType) {
		String fontPath = fontType.getPath();

		if (!typefaceCache.containsKey(fontType)) {
			typefaceCache.put(fontType, Typeface.createFromAsset(context.getAssets(), fontPath));
		}

		return typefaceCache.get(fontType);
	}

	/**
	 * Gets roboto typeface according to passed typeface style settings.
	 * <p/>
	 * Will get Roboto-Bold for Typeface.BOLD etc
	 */
	private static Typeface getRobotoTypeface(Context context, Object tag) {

		FontType robotoFontType = null;

		if ("bold".equals(tag)) {
			robotoFontType = FontType.BOLD;
		} else if ("light".equals(tag)) {
			robotoFontType = FontType.LIGHT;
		} else if ("condensed".equals(tag)) {
			robotoFontType = FontType.CONDENSED;
		} else {
			robotoFontType = FontType.NORMAL;
		}

		return getRobotoTypeface(context, robotoFontType);
	}

	/**
	 * Walks ViewGroups, finds TextViews and applies Typefaces taking styling in consideration
	 *
	 * @param context - to reach assets
	 * @param view    - root view to apply typeface to
	 */
	public static void setRobotoFont(Context context, View view) {
		if (view instanceof ViewGroup) {
			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
				setRobotoFont(context, ((ViewGroup) view).getChildAt(i));
			}
		} else if (view instanceof TextView) {
			((TextView) view).setTypeface(getRobotoTypeface(context, view.getTag()));
		}
	}

}
